package com.sinvo.oa.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinvo.oa.entity.model.process.ProcessTemplate;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.log.annotation.Log;
import com.sinvo.oa.log.enums.ServiceType;
import com.sinvo.oa.result.R;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.ProcessTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 审批模板控制器
 */
@Api(tags = "审批模板管理")
@RestController
@RequestMapping("admin/process/processTemplate")
public class ProcessTemplateController {

    @Autowired
    private ProcessTemplateService processTemplateService;

    /**
     * 分页获取审批模板
     *
     * @param pageNum  当前页
     * @param pageSize 页大小
     * @return R
     */
    @PreAuthorize("hasAuthority('btn.processTemplate.list')")
    @ApiOperation("分页获取审批模板")
    @GetMapping("{pageNum}/{pageSize}")
    public R page(@PathVariable Long pageNum, @PathVariable Long pageSize) {
        Page<ProcessTemplate> page = new Page<>(pageNum, pageSize);
        //分页查询审批模板 需要typeId->name
        page = processTemplateService.selectPageProcessTemplate(page);
        return R.success(page);
    }

    /**
     * 根据id获取
     *
     * @param id templateId
     * @return R
     */
    @PreAuthorize("hasAuthority('btn.processTemplate.list')")
    @ApiOperation(value = "获取")
    @GetMapping("get/{id}")
    public R get(@PathVariable Long id) {
        //验证参数
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "非法参数");
        }
        ProcessTemplate processTemplate = processTemplateService.getById(id);
        return R.success(processTemplate);
    }

    /**
     * 新增模板
     *
     * @param processTemplate
     * @return R
     */
    @Log(title = "审批模板管理",businessType = ServiceType.INSERT)
    @PreAuthorize("hasAuthority('btn.processTemplate.templateSet')")
    @ApiOperation(value = "新增")
    @PostMapping("save")
    public R save(@Validated @RequestBody ProcessTemplate processTemplate, BindingResult result) {
        if (result.hasErrors()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "非法参数");
        }
        //保存审批模板
        processTemplateService.saveTemplate(processTemplate);
        return R.success();
    }

    /**
     * 修改模板
     *
     * @param processTemplate
     * @return R
     */
    @Log(title = "审批模板管理",businessType = ServiceType.UPDATE)
    @PreAuthorize("hasAuthority('btn.processTemplate.templateSet')")
    @ApiOperation(value = "修改")
    @PutMapping("update")
    public R updateById(@Validated @RequestBody ProcessTemplate processTemplate, BindingResult result) {
        if (result.hasErrors()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "非法参数");
        }
        //更新模板
        processTemplateService.updateTemplate(processTemplate);
        return R.success();
    }

    /**
     * 根据id删除模板
     *
     * @param id templateId
     * @return R
     */
    @Log(title = "审批模板管理",businessType = ServiceType.DELETE)
    @PreAuthorize("hasAuthority('btn.processTemplate.remove')")
    @ApiOperation(value = "删除")
    @DeleteMapping("remove/{id}")
    public R remove(@PathVariable Long id) {
        //验证参数
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "非法参数");
        }
        processTemplateService.removeById(id);
        return R.success();
    }

    /**
     * 上传流程 zip文件 文件命名 xxx.zip 其中xxx与bpmn文件中process id="xxx"一致
     * @param file
     * @return R
     * @throws IOException
     */
    @Log(title = "审批模板管理",businessType = ServiceType.OTHER)
    @PreAuthorize("hasAuthority('btn.processTemplate.templateSet')")
    @ApiOperation(value = "上传流程")
    @PostMapping("/uploadProcessDefinition")
    public R uploadProcessDefinition(MultipartFile file) throws IOException {
        String path = new File(ResourceUtils.getURL("classpath:").getPath()).getAbsolutePath();
        //设置编码 因为路径带有中文
        path = URLDecoder.decode(path, "UTF-8");
        //上传文件夹
        File destFolder = new File(path + "/process");
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }
        //创建文件
        String filename = file.getOriginalFilename();
        File destFile = new File(path + "/process/" + filename);
        //文件写入
        file.transferTo(destFile);
        Map<String, Object> map = new HashMap<>();
        //返回文件路径和文件名称
        map.put("processDefinitionPath", "process/" + filename);
        map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
        return R.success(map);
    }

    /**
     * 发布模板 也就是activiti部署流程定义
     * @param id
     * @return
     */
    @Log(title = "审批模板管理",businessType = ServiceType.OTHER)
    @PreAuthorize("hasAuthority('btn.processTemplate.publish')")
    @ApiOperation(value = "发布")
    @GetMapping("publish/{id}")
    public R publish(@PathVariable Long id){
        //验证参数
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "非法参数");
        }
        //调用方法 status代表发布
        processTemplateService.publish(id);
        return R.success();
    }

}

